const express = require('express');
const { Op, sequelize } = require('sequelize');
const { Feed, User, Activity, FeedLike, FeedComment } = require('../models');
const { authenticateToken, optionalAuth } = require('../middleware/auth');
const { validateFeedCreation, validatePagination } = require('../middleware/validation');

const router = express.Router();

// 获取时间线动态
router.get('/', optionalAuth, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 50;
    const offset = (page - 1) * limit;
    const { feed_type, user_id } = req.query;

    const whereConditions = {
      is_public: true
    };

    // 动态类型筛选
    if (feed_type) {
      whereConditions.feed_type = feed_type;
    }

    // 用户筛选
    if (user_id) {
      whereConditions.user_id = user_id;
    }

    const { count, rows: feeds } = await Feed.findAndCountAll({
      where: whereConditions,
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar_url']
        },
        {
          model: Activity,
          as: 'activity',
          attributes: ['id', 'title', 'location', 'start_time'],
          required: false
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      feeds,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取动态列表失败:', error);
    res.status(500).json({
      error: '获取动态列表失败'
    });
  }
});

// 获取用户个人时间线
router.get('/timeline', authenticateToken, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 50;
    const offset = (page - 1) * limit;

    // 获取用户关注的人的动态
    // 这里简化处理，实际项目中需要实现关注系统
    const { count, rows: feeds } = await Feed.findAndCountAll({
      where: {
        [Op.or]: [
          { user_id: req.user.id }, // 自己的动态
          { is_public: true } // 公开动态
        ]
      },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar_url']
        },
        {
          model: Activity,
          as: 'activity',
          attributes: ['id', 'title', 'location', 'start_time'],
          required: false
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      feeds,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取个人时间线失败:', error);
    res.status(500).json({
      error: '获取个人时间线失败'
    });
  }
});

// 发布动态
router.post('/', authenticateToken, validateFeedCreation, async (req, res) => {
  try {
    const {
      content,
      media_urls,
      feed_type,
      activity_id,
      is_public
    } = req.body;

    // 如果关联活动，验证活动是否存在
    if (activity_id) {
      const activity = await Activity.findByPk(activity_id);
      if (!activity) {
        return res.status(404).json({
          error: '关联的活动不存在'
        });
      }
    }

    const feed = await Feed.create({
      user_id: req.user.id,
      content,
      media_urls,
      feed_type: feed_type || 'post',
      activity_id,
      is_public: is_public !== undefined ? is_public : true
    });

    // 获取完整的动态信息
    const fullFeed = await Feed.findByPk(feed.id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar_url']
        },
        {
          model: Activity,
          as: 'activity',
          attributes: ['id', 'title', 'location', 'start_time'],
          required: false
        }
      ]
    });

    // 通过Socket.IO广播新动态
    const io = req.app.get('io');
    if (feed.is_public) {
      io.emit('new_feed', fullFeed);
    }

    res.status(201).json({
      message: '动态发布成功',
      feed: fullFeed
    });
  } catch (error) {
    console.error('发布动态失败:', error);
    res.status(500).json({
      error: '发布动态失败',
      details: error.message
    });
  }
});

// 获取单个动态详情
router.get('/:id', optionalAuth, async (req, res) => {
  try {
    const feed = await Feed.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar_url']
        },
        {
          model: Activity,
          as: 'activity',
          attributes: ['id', 'title', 'location', 'start_time'],
          required: false
        }
      ]
    });

    if (!feed) {
      return res.status(404).json({
        error: '动态不存在'
      });
    }

    // 检查访问权限
    if (!feed.is_public && (!req.user || req.user.id !== feed.user_id)) {
      return res.status(403).json({
        error: '无权限查看此动态'
      });
    }

    res.json({
      feed
    });
  } catch (error) {
    console.error('获取动态详情失败:', error);
    res.status(500).json({
      error: '获取动态详情失败'
    });
  }
});

// 更新动态
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const feed = await Feed.findByPk(req.params.id);

    if (!feed) {
      return res.status(404).json({
        error: '动态不存在'
      });
    }

    // 检查权限
    if (feed.user_id !== req.user.id) {
      return res.status(403).json({
        error: '无权限修改此动态'
      });
    }

    const { content, media_urls, is_public } = req.body;

    await feed.update({
      content: content !== undefined ? content : feed.content,
      media_urls: media_urls !== undefined ? media_urls : feed.media_urls,
      is_public: is_public !== undefined ? is_public : feed.is_public
    });

    res.json({
      message: '动态更新成功',
      feed
    });
  } catch (error) {
    console.error('更新动态失败:', error);
    res.status(500).json({
      error: '更新动态失败'
    });
  }
});

// 删除动态
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const feed = await Feed.findByPk(req.params.id);

    if (!feed) {
      return res.status(404).json({
        error: '动态不存在'
      });
    }

    // 检查权限
    if (feed.user_id !== req.user.id) {
      return res.status(403).json({
        error: '无权限删除此动态'
      });
    }

    await feed.destroy();

    res.json({
      message: '动态删除成功'
    });
  } catch (error) {
    console.error('删除动态失败:', error);
    res.status(500).json({
      error: '删除动态失败'
    });
  }
});

// 点赞动态
router.post('/:id/like', authenticateToken, async (req, res) => {
  try {
    const feedId = parseInt(req.params.id);

    // 检查动态是否存在
    const feed = await Feed.findByPk(feedId);
    if (!feed) {
      return res.status(404).json({
        error: '动态不存在'
      });
    }

    // 检查是否已经点赞
    const existingLike = await FeedLike.findOne({
      where: {
        user_id: req.user.id,
        feed_id: feedId
      }
    });

    if (existingLike) {
      return res.status(400).json({
        error: '已经点赞过了'
      });
    }

    // 创建点赞记录
    await FeedLike.create({
      user_id: req.user.id,
      feed_id: feedId
    });

    // 更新动态点赞数
    await feed.increment('likes_count');

    res.json({
      message: '点赞成功'
    });
  } catch (error) {
    console.error('点赞失败:', error);
    res.status(500).json({
      error: '点赞失败'
    });
  }
});

// 取消点赞
router.delete('/:id/like', authenticateToken, async (req, res) => {
  try {
    const feedId = parseInt(req.params.id);

    const like = await FeedLike.findOne({
      where: {
        user_id: req.user.id,
        feed_id: feedId
      }
    });

    if (!like) {
      return res.status(404).json({
        error: '未点赞该动态'
      });
    }

    // 删除点赞记录
    await like.destroy();

    // 更新动态点赞数
    const feed = await Feed.findByPk(feedId);
    if (feed && feed.likes_count > 0) {
      await feed.decrement('likes_count');
    }

    res.json({
      message: '取消点赞成功'
    });
  } catch (error) {
    console.error('取消点赞失败:', error);
    res.status(500).json({
      error: '取消点赞失败'
    });
  }
});

// 获取动态点赞列表
router.get('/:id/likes', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const { count, rows: likes } = await FeedLike.findAndCountAll({
      where: { feed_id: req.params.id },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar_url']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    const users = likes.map(like => like.user);

    res.json({
      users,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取点赞列表失败:', error);
    res.status(500).json({
      error: '获取点赞列表失败'
    });
  }
});

// 添加评论
router.post('/:id/comments', authenticateToken, async (req, res) => {
  try {
    const feedId = parseInt(req.params.id);
    const { content, parent_id } = req.body;

    if (!content || content.trim().length === 0) {
      return res.status(400).json({
        error: '评论内容不能为空'
      });
    }

    if (content.length > 500) {
      return res.status(400).json({
        error: '评论内容不能超过500字符'
      });
    }

    // 检查动态是否存在
    const feed = await Feed.findByPk(feedId);
    if (!feed) {
      return res.status(404).json({
        error: '动态不存在'
      });
    }

    // 如果是回复，检查父评论是否存在
    if (parent_id) {
      const parentComment = await FeedComment.findOne({
        where: { 
          id: parent_id, 
          feed_id: feedId,
          is_deleted: false
        }
      });
      if (!parentComment) {
        return res.status(400).json({
          error: '回复的评论不存在'
        });
      }
    }

    // 创建评论
    const comment = await FeedComment.create({
      user_id: req.user.id,
      feed_id: feedId,
      content: content.trim(),
      parent_id: parent_id || null
    });

    // 更新动态评论数
    await feed.increment('comments_count');

    // 获取完整的评论信息返回
    const newComment = await FeedComment.findByPk(comment.id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar_url']
        }
      ]
    });

    res.status(201).json({
      message: '评论成功',
      comment: newComment
    });
  } catch (error) {
    console.error('添加评论失败:', error);
    res.status(500).json({
      error: '添加评论失败'
    });
  }
});

// 获取动态评论列表
router.get('/:id/comments', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const { count, rows: comments } = await FeedComment.findAndCountAll({
      where: { 
        feed_id: req.params.id,
        parent_id: null, // 只获取顶级评论
        is_deleted: false
      },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar_url']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      comments,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取评论列表失败:', error);
    console.error('错误详情:', error.message);
    res.status(500).json({
      error: '获取评论列表失败',
      details: error.message
    });
  }
});

// 删除评论
router.delete('/comments/:commentId', authenticateToken, async (req, res) => {
  try {
    const commentId = parseInt(req.params.commentId);

    const comment = await FeedComment.findByPk(commentId);
    if (!comment) {
      return res.status(404).json({
        error: '评论不存在'
      });
    }

    // 检查权限：只能删除自己的评论
    if (comment.user_id !== req.user.id) {
      return res.status(403).json({
        error: '无权限删除此评论'
      });
    }

    // 软删除评论
    await comment.update({ is_deleted: true });

    // 更新动态评论数
    const feed = await Feed.findByPk(comment.feed_id);
    if (feed && feed.comments_count > 0) {
      await feed.decrement('comments_count');
    }

    res.json({
      message: '评论删除成功'
    });
  } catch (error) {
    console.error('删除评论失败:', error);
    res.status(500).json({
      error: '删除评论失败'
    });
  }
});

// 检查用户是否点赞了某个动态
router.get('/:id/like-status', authenticateToken, async (req, res) => {
  try {
    const feedId = parseInt(req.params.id);

    const like = await FeedLike.findOne({
      where: {
        user_id: req.user.id,
        feed_id: feedId
      }
    });

    res.json({
      isLiked: !!like
    });
  } catch (error) {
    console.error('检查点赞状态失败:', error);
    res.status(500).json({
      error: '检查点赞状态失败'
    });
  }
});

// 获取用户动态统计
router.get('/stats/:userId', async (req, res) => {
  try {
    const userId = req.params.userId;

    const stats = await Feed.findAll({
      where: { user_id: userId },
      attributes: [
        'feed_type',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['feed_type']
    });

    const totalFeeds = await Feed.count({
      where: { user_id: userId }
    });

    const totalLikes = await Feed.sum('likes_count', {
      where: { user_id: userId }
    });

    const totalComments = await Feed.sum('comments_count', {
      where: { user_id: userId }
    });

    res.json({
      stats,
      summary: {
        totalFeeds,
        totalLikes: totalLikes || 0,
        totalComments: totalComments || 0
      }
    });
  } catch (error) {
    console.error('获取用户动态统计失败:', error);
    res.status(500).json({
      error: '获取用户动态统计失败'
    });
  }
});

module.exports = router; 